/**
 * 主要用于显示User Model数据
 * 实现了数据的展示与删除功能
 * 数据展示：
 * 数据删除：
 */
import React, { Component } from 'react';
import { withRouter } from 'react-router-dom';
import { Grid, Table, Pagination, Button } from 'semantic-ui-react';
import BusiCrumb from '../../../menu/crumb/BusiCrumb';
import axios from 'axios';
import moment from 'moment';
import jwt_decode from 'jwt-decode';
import './UserTable.css';

class UserTable extends Component {
    constructor() {
        super();
        this.state = {
            userdata: null,
            pageItemCount: 15,
            activePage: 1,
            boundaryRange: 0,
            siblingRange: 1,
            showEllipsis: true,
            showFirstAndLastNav: true,
            showPreviousAndNextNav: true,
            totalPages: 1,
        }
    }

    componentDidMount() {
        // 默认显示第1页
        this.getUserList(0);
    }

    getUserList = (offset) => {
        // 获取用户信息时将token添加在headers中发送
        axios.get("/api/auth/user?offset=" + offset + "&limit=" + this.state.pageItemCount , {
            headers: {
                'Authorization': 'Bearer ' + localStorage.usertoken,
                'Content-Type': 'application/x-www-form-urlencoded'
            }
        }).then(res => {
            this.setState({
                userdata: res.data.results,
                totalPages: Number.isInteger(res.data.count / this.state.pageItemCount) ?  Math.floor(res.data.count / this.state.pageItemCount) : Math.floor(res.data.count / this.state.pageItemCount) + 1,  
            });
        }).catch(err => {
            console.log(err);
        });
    }

    // pagination时处理翻页
    setActivePage = (activePage) => {
        this.setState({ activePage: activePage });
        this.getUserList(( activePage - 1) * this.state.pageItemCount );
    }

    handlePaginationChange = (e, { activePage }) => {
        this.setActivePage(activePage);
    }
    
    // 删除按钮触发事件
    deleteClick(id) {
        axios.delete("/api/auth/user/"+ id, {
            headers: {
                'Authorization': 'Bearer ' + localStorage.usertoken,
                'Content-Type': 'application/x-www-form-urlencoded'
            }
        }).then(res => {
            if (res.data.success) {
                this.getUserList(( this.state.activePage - 1) * this.state.pageItemCount);
            }
        }).catch(err => {
            console.log(err);
        });
    }

    editClick(id) {
        this.props.history.push('/useredit/' + id);
    }

    render() {
        const {
            activePage,
            boundaryRange,
            siblingRange,
            showEllipsis,
            showFirstAndLastNav,
            showPreviousAndNextNav,
            totalPages,
        } = this.state
        // 判断是否为Admin，以此确定是否有删除和修改属性的权力
        const isAdmin = jwt_decode(localStorage.usertoken).role === 'Admin' ? true : false;

        return (
            <Grid >
                <Grid.Row>
                    <Grid.Column>
                        <BusiCrumb></BusiCrumb>
                    </Grid.Column>
                </Grid.Row>
                <Grid.Row>
                    <Grid.Column>
                        <Table celled>
                            <Table.Header>
                                <Table.Row>
                                    <Table.HeaderCell>ID</Table.HeaderCell>
                                    <Table.HeaderCell>电子邮件</Table.HeaderCell>
                                    <Table.HeaderCell>用户名称</Table.HeaderCell>
                                    <Table.HeaderCell>角色</Table.HeaderCell>
                                    <Table.HeaderCell>是否活跃</Table.HeaderCell>
                                    <Table.HeaderCell>创建时间</Table.HeaderCell>
                                    {isAdmin ? (<Table.HeaderCell>活动</Table.HeaderCell>) : ('')}
                                </Table.Row>
                            </Table.Header>
                            <Table.Body>{this.state.userdata ? (
                                    this.state.userdata.map((user, index) => {
                                        return (
                                            <Table.Row key={index}>
                                                <Table.Cell collapsing>{index+1}</Table.Cell>
                                                <Table.Cell>{user.email}</Table.Cell>
                                                <Table.Cell>{user.username}</Table.Cell>
                                                <Table.Cell>{user.role}</Table.Cell>
                                                <Table.Cell>{ user.isActive ? '是' : '否'}</Table.Cell>
                                                <Table.Cell>{ moment(user.createdAt).format("YYYY-MM-DD")}</Table.Cell>
                                                {isAdmin ? (<Table.Cell collapsing >
                                                    <Button primary icon="edit" onClick={(e, props, id) => this.editClick(user.id)}  ></Button>
                                                    <Button primary icon="delete" onClick={(e, props, id) => this.deleteClick(user.id)}></Button>
                                                </Table.Cell>) : ('')}
                                            </Table.Row>
                                        )
                                    })
                            ) : "无数据..."}</Table.Body>
                            <Table.Footer>
                                <Table.Row>
                                    <Table.HeaderCell colSpan='7'>
                                    <Pagination
                                        activePage={activePage}
                                        boundaryRange={boundaryRange}
                                        onPageChange={this.handlePaginationChange}
                                        size='mini'
                                        siblingRange={siblingRange}
                                        totalPages={totalPages}
                                        // Heads up! All items are powered by shorthands, if you want to hide one of them, just pass `null` as value
                                        ellipsisItem={showEllipsis ? undefined : null}
                                        firstItem={showFirstAndLastNav ? undefined : null}
                                        lastItem={showFirstAndLastNav ? undefined : null}
                                        prevItem={showPreviousAndNextNav ? undefined : null}
                                        nextItem={showPreviousAndNextNav ? undefined : null}
                                    />
                                    </Table.HeaderCell>
                                </Table.Row>
                            </Table.Footer>
                        </Table>
                    </Grid.Column>
                </Grid.Row>
            </Grid>
        );
    }
}
export default withRouter(UserTable);